from src.common.logger import getLogger
from src.agentic.agent.AgentTools import AgentTools
from src.agentic.config.LanguageModel import LanguageModel
from src.agentic.agent.pattern.ReActAgent import ReActAgent
from src.agentic.agent.pattern.ReWOOAgent import ReWOOAgent
from src.agentic.agent.pattern.ReflexionAgent import ReflexionAgent
from src.agentic.agent.pattern.ReflectionAgent import ReflectionAgent
from src.agentic.agent.pattern.PlanExecuteAgent import PlanExecuteAgent
from src.agentic.agent.pattern.SelfDiscoverAgent import SelfDiscoverAgent
from src.modules.memory.service import HistoryRecordService, MemoryDetailService

logger = getLogger()

def invoke_agent(args):

    HistoryRecordService.insert_history_memory(args)

    base_url = "http://localhost:11434"
    llm_model = LanguageModel("qwen3:4b", base_url, None)
    llm = llm_model.new_llm_model()

    agent_tools = AgentTools()
    tools = agent_tools.get_execute_tools()

    query = args.get("query")
    logger.info(f"invoke_agent query: {query}")

    agent = None
    agent_pattern = args.get("pattern")
    if agent_pattern == "ReAct":
        agent = ReActAgent(llm, tools, 3)
    elif agent_pattern == "ReWOO":
        agent = ReWOOAgent(llm, tools)
    elif agent_pattern == "PlanExecute":
        agent = PlanExecuteAgent(llm, tools)
    elif agent_pattern == "Reflection":
        agent = ReflectionAgent(llm, tools, 2)
    elif agent_pattern == "SelfDiscover":
        agent = SelfDiscoverAgent(llm, tools)
    elif agent_pattern == "Reflexion":
        agent = ReflexionAgent(llm, tools, 2)
    response = agent.invoke(query)

    MemoryDetailService.insert_memory_detail_ai(args, response)

    logger.info(f"invoke_agent response len: {len(response)}")
    return response
